import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { PageService } from 'app/utils/page.service'
import { ProjectManageService } from 'app/services/manage/project-manage.service'

@Component({
  selector: 'app-project-manage',
  templateUrl: './project-manage.component.html',
  styleUrls: ['./project-manage.component.less']
})
export class ProjectManageComponent implements OnInit {

  private projectForm: FormGroup
  private dataSet: Array<any> = []

  constructor(
    private page: PageService,
    private projectManageService: ProjectManageService,
    private modalService: NzModalService,
    private messageService: NzMessageService,
    private fb: FormBuilder
  ) {
    this.projectForm = fb.group({
      name: []
    })
  }

  ngOnInit() {
    this.refreshData()
  }

  /**
   * 刷新数据
   */
  refreshData() {
    this.projectManageService.getProjects(this.page)
      .then((data: any) => data.map(x => ({
        id: x.id,
        name: x.get('name'),
        createAt: x.createdAt
      })))
      .then((data: any) => {
        this.dataSet = data
      })
  }

  /**
   * 显示项目详情弹窗
   */
  showProjectDialog(content, data) {
    let title = ''

    if (data) {
      title = '修改项目'
      this.projectForm.setValue({
        name: data.name
      })
    } else {
      title = '新建项目'
      this.projectForm.reset()
    }

    let model = this.modalService.open({
      title: title,
      content: content,
      maskClosable: false,
      onOk: () => {
        this.projectManageService.saveProject({
          name: this.projectForm.value.name
        }, data ? data.id : '').then(() => {
          this.refreshData()
          this.messageService.create('success', '保存成功')
        })
      }
    });
  }

  /**
   * 删除项目
   */
  deleteProject(id) {
    this.projectManageService.deleteProject(id)
      .then(() => {
        this.refreshData()
        this.messageService.create('success', '删除成功')
      }, error => {
        console.log(error)
      })
  }
}
